package com.google.qam.app;

import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.DisplayMetrics;
import android.widget.Toast;

public class App {
	static private final HashMap<Context, App> mMap = new HashMap<Context, App>();

	static public App get(Context context) {
		return mMap.get(context);
	}

	public static float PIXEL_DENSITY = 0.0f;

	private final Context mContext;
	private final HandlerThread mHandlerThread = new HandlerThread("AppHandlerThread");
	private final Handler mHandler;

	public App(Context context) {
		// register
		mMap.put(context, this);

		mContext = context;

		if (PIXEL_DENSITY == 0.0f) {
			DisplayMetrics metrics = new DisplayMetrics();
			((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(metrics);
			PIXEL_DENSITY = metrics.density;
		}

		mHandlerThread.start();
		mHandler = new Handler(mHandlerThread.getLooper());
	}

	public void shutdown() {
		// unregister
		mMap.put(mContext, null);
	}

	public Context getContext() {
		return mContext;
	}

	public Handler getHandler() {
		while (mHandler == null) {
			// Wait till the handler is created.
			;
		}
		return mHandler;
	}

	public void showToast(final String string, final int duration) {
		mHandler.post(new Runnable() {
			public void run() {
				Toast.makeText(mContext, string, duration).show();
			}
		});
	}
}
